<template>
  <picker
    @change="handleChange"
    :value="index"
    :range="options"
    :range-key="rangeKey"
    :mode="mode"
    :disabled="disabled"
  >
    <view class="chooseType">
      <text>{{ currentValue || placeholoder }}</text>
      <text class="iconfont icon-arrow-right"></text>
    </view>
  </picker>
</template>

<script>
export default {
  name: "myPicker",
  props: {
    value: String | Number,
    options: Array,
    rangeKey: String,
    rangeValue: {
      type: String,
      default: "value",
    },
    placeholoder: {
      type: String,
      default: "请选择",
    },
    mode: {
      type: String,
      default: "selector",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      index: -1,
      strValue: "",
    };
  },
  computed: {
    currentValue() {
      if (this.mode == "selector") {
        if (this.rangeKey) {
          return this.index == -1
            ? ""
            : this.options[this.index][this.rangeKey];
        } else {
          return this.options[this.index];
        }
      }
      if (this.mode == "time" || this.mode == "date") {
        return this.strValue;
      }
    },
  },
  watch: {
    value(val) {
      if (this.mode == "selector") {
        this.index = this.rangeKey
          ? this.options.findIndex((item) => item[this.rangeValue] == val)
          : this.options.findIndex((item) => item == val);
      }
      if (this.mode == "time" || this.mode == "date") {
        this.strValue = val;
      }
    },
  },
  mounted() {
    if (this.mode == "selector") {
      this.index = this.rangeKey
        ? this.options.findIndex((item) => item[this.rangeValue] == this.value)
        : this.options.findIndex((item) => item == this.value);
    }
    if (this.mode == "time" || this.mode == "date") {
      this.strValue = this.value;
    }
  },
  methods: {
    handleChange(e) {
      if (this.mode == "selector") {
        this.index = e.target.value;
        let currentValue = this.rangeKey
          ? this.options[this.index][this.rangeValue]
          : this.options[this.index];
        this.$emit("input", currentValue);
      }
      if (this.mode == "time" || this.mode == "date") {
        this.strValue = e.detail.value;
        this.$emit("input", this.strValue);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.chooseType {
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: #262626;
  font-size: 28rpx;
  .iconfont {
    font-size: 20rpx;
    color: #888;
  }
}
</style>